﻿using Kinlo.MESDocking;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using UIWindows.Views;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace UIWindows.ViewModels.Dialogs
{
    public class MesInfoViewModel : ViewModelBase
    {
        public string UserName { get; set; }
        public string EquipmentCode { get; set; }
        public string process_id { get; set; }
        public string Steptype { get; set; }
        public string StepNumber { get; set; }
        //public string Class { get; set; }
        //public string ClassTeam { get; set; }
        public string ProductMark { get; set; }
        public string WorkOrder { get; set; }
        public string BatchNo { get; set; }
        public string EmpNo { get; set; }
        IContainer Container;
        //public MesCFG MesCFG { get; set; }
        //private MESVoid mes;
        /// <summary>
        /// 工单下拉选择集合
        /// </summary>
        public ObservableCollection<ComboxItem> Workorders { get; set; }
        /// <summary>
        /// 产品标志下拉选择集合
        /// </summary>
        public ObservableCollection<ComboxItem> ProductMarks { get; set; }

        public List<string> lstBill_No = new List<string>();
        public List<string> lstMaterial_Code = new List<string>();
        public List<string> lstMaterial_Spec = new List<string>();
        public List<string> lstPC_No = new List<string>();
        public List<string> lstWorkOrderStatus_Name = new List<string>();
        public List<string> lstPlanedStart = new List<string>();
        public List<string> lstPlanedEndDate = new List<string>();
        public List<string> lstProductionOrderNO = new List<string>();

        public ParameterStatic _parameterStatic { get; set; }
        public MESCollectionItemsParameterModel _mesParameter { get; set; }
        public MESUserNameCheck mesUserInteraction { get; set; }

        GetByProductCodeInterface interaction;

        private Window _window;

        public ShiftTypes _classValue;
        public ShiftTypes ClassValue
        {
            get { return _classValue; }
            set
            {
                if (_classValue != value) ;

                //MachineInfoValueSelect(MachineInfoValue, value);
                _classValue = value;
                OnPropertyChanged(nameof(ClassValue));
            }
        }

        public List<object> ClassList { get; set; } = new List<object>();

        public ClassTeamTypes _classTeamValue;
        public ClassTeamTypes ClassTeamValue
        {
            get { return _classTeamValue; }
            set
            {
                if (_classTeamValue != value) ;

                //MachineInfoValueSelect(MachineInfoValue, value);
                _classTeamValue = value;
                OnPropertyChanged(nameof(ClassTeamValue));
            }
        }

        public List<object> ClassTeamList { get; set; } = new List<object>();


        public MesInfoViewModel(ParameterStatic parameterStatic, Window window)
        {
            _window = window;
            _parameterStatic = parameterStatic;

            if (!parameterStatic.MESCollectionItemsParameter.ContainsKey(MachineInfoTypes.预充装盘))
            {
                parameterStatic.MESCollectionItemsParameter.Add(MachineInfoTypes.预充装盘, new MESCollectionItemsParameterModel());
            }
            _mesParameter = parameterStatic.MESCollectionItemsParameter[MachineInfoTypes.预充装盘];

            ClassList.AddRange(Enum.GetValues(typeof(ShiftTypes)).Cast<object>());
            ClassTeamList.AddRange(Enum.GetValues(typeof(ClassTeamTypes)).Cast<object>());


            interaction = new GetByProductCodeInterface(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
            mesUserInteraction = new MESUserNameCheck(DialogLogHelper.MesLog, DialogLogHelper.MESDialog);
            ProductMarks = new ObservableCollection<ComboxItem>
            {
                // 添加空选项
                new ComboxItem { Name = " ", Value = " " }
            };

            // 添加字符A到E的所有字母
            for (char c = 'A'; c <= 'E'; c++)
            {

                ProductMarks.Add(new ComboxItem { Name = c.ToString(), Value = c.ToString() });
            }
            Init();
        }
        void Init()
        {
            try
            {
                UserName = _mesParameter.UserName;
                EquipmentCode = _mesParameter.EquipmentCode;
                process_id = _mesParameter.process_id;
                Steptype = _mesParameter.Steptype;
                StepNumber = _mesParameter.StepNumber;
                //Class = _mesParameter.Class;
                //ClassTeam = _mesParameter.ClassTeam;
                ClassValue = (ShiftTypes)(int.Parse(_mesParameter.Class));
                ClassTeamValue = (ClassTeamTypes)(int.Parse(_mesParameter.ClassTeam));

                WorkOrder = _mesParameter.WorkOrder;

                Material_Spec = _mesParameter.Material_Spec;

                BatchNo = _mesParameter.BatchNo;
                EmpNo = _mesParameter.EmpNo;

                ProductMark = _mesParameter.ProductMark;

                Workorders = new ObservableCollection<ComboxItem>();
                WorkorderSelectedValue = WorkOrder;

                ProductMarkSelectedValue = ProductMark;

              

            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //获取工单
            CmdWorkOrder.Execute();
        }
     
        public Commands.DelegateCommand CmdWorkOrder => new  Commands.DelegateCommand(async () =>
        {
            try
            {
                //获取工单当前产品选择空
                //ProductMarkSelectedValue = " ";
                Workorders.Clear();
                lstBill_No = new List<string>();
                lstMaterial_Code = new List<string>();
                lstMaterial_Spec = new List<string>();
                lstPC_No = new List<string>();
                lstWorkOrderStatus_Name = new List<string>();
                lstPlanedStart = new List<string>();
                lstPlanedEndDate = new List<string>();
                lstProductionOrderNO = new List<string>();



                Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                       {"equipment_id",EquipmentCode },
                        {"process_id",process_id }
                    };


                var result = await interaction.MESInteractionAsync(_parameterStatic.MESParameter.GetByProductCodeRoute,
                         _parameterStatic.MESParameter.GetByProductCodeTime,
                         1, DateTime.Now, mesParam);

                if (result == ResultTypes.合格)
                {

                    object resultValue = mesParam["result"];

                    // 检查值的类型是否是 List<Dictionary<string, object>>
                    if (resultValue is List<Dictionary<string, object>> resultList)
                    {
                        // 现在你可以使用 resultList，比如获取长度
                        int resultListLength = resultList.Count;

                        for (int i = 0, j = 0; i < resultListLength; i++)
                        {


                            Workorders.Add(new ComboxItem { Name = resultList[i]["Bill_No"]?.ToString() ?? "", Value = resultList[i]["Bill_No"]?.ToString() ?? "" });
                            lstBill_No.Add(resultList[i]["Bill_No"]?.ToString() ?? "");
                            lstMaterial_Code.Add(resultList[i]["Material_Code"]?.ToString() ?? "");
                            lstMaterial_Spec.Add(resultList[i]["Material_Spec"]?.ToString() ?? "");
                            lstPC_No.Add(resultList[i]["PC_No"]?.ToString() ?? "");
                            lstWorkOrderStatus_Name.Add(resultList[i]["WorkOrderStatus_Name"]?.ToString() ?? "");
                            lstPlanedStart.Add(resultList[i]["PlanedStart"]?.ToString() ?? "");
                            lstPlanedEndDate.Add(resultList[i]["PlanedEndDate"]?.ToString() ?? "");
                            lstProductionOrderNO.Add(resultList[i]["ProductionOrderNO"]?.ToString() ?? "");
                        }
                        if(Workorders.Any(x=>x.Name==_mesParameter.WorkOrder))
                        {
                            WorkorderSelectedValue = _mesParameter.WorkOrder;
                        }
                        
                        DoCmdOrderSelectionChanged();

                        $"工单获取成功".RunLog(MessageLevelType.成功);
                    }
                    else
                    {
                        $"工单数据转换List字典失败：{resultValue}".RunLog(MessageLevelType.错误);
                    }
                }
                else
                {
                    $"工单获取失败".RunLog(MessageLevelType.错误);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"工单发生错误,错误信息:{ex.Message}");
            }
        });


        public Commands.DelegateCommand CmdSave => new Commands.DelegateCommand(() =>
        {

            if (!string.IsNullOrWhiteSpace(ProductMarkSelectedValue))
            {
                if (MessageBox.Show($"是否确认保存？当前产品标志为：{ProductMarkSelectedValue}", "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    // 在这里添加您的代码
                }
                else
                {
                    return;
                }
            }
            //是否切换工单
            bool isChangeWorkOrder = _mesParameter.WorkOrder != WorkorderSelectedValue;
            //是否切换班组或者班次
            bool isChangeShift = (_mesParameter.Class != ((int)ClassValue).ToString() || _mesParameter.ClassTeam != ((int)ClassTeamValue).ToString());
            //是否切换工号
            bool isChangeEmployeeId = false;

            //if (_mesParameter.HasValidEmployeeId == 0 || (_mesParameter.HasValidUserName == null || _mesParameter.HasValidUserName != UserName))
            //{
            //    MessageBox.Show("未校验工号！！！");
            //    return;
            //}
            //else if (_mesParameter.HasValidEmployeeId == 2)
            //{
            //    MessageBox.Show("工号校验失败，请更换工号或联系管理员！！！");
            //    return;
            //}
            //else
            //{
            //  
            //}
            isChangeEmployeeId = _mesParameter.UserName != UserName;

            if (isChangeWorkOrder || isChangeShift || isChangeEmployeeId)
            {
                this.MESCountUpLoad_Hour();
                "切换工单或班组班次成功".RunLog(MessageLevelType.成功);
            }


            _mesParameter.UserName = UserName;
            _mesParameter.EquipmentCode = EquipmentCode;
            _mesParameter.process_id = process_id;
            _mesParameter.Steptype = Steptype;
            _mesParameter.StepNumber = StepNumber;
            _mesParameter.Class = ((int)ClassValue).ToString();

            _mesParameter.ClassTeam = ((int)ClassTeamValue).ToString();
            
            //_mesParameter.ClassTeam = ClassTeam;


            _mesParameter.ProductMark = ProductMarkSelectedValue;
            _mesParameter.WorkOrder = WorkorderSelectedValue;

            _mesParameter.Material_Spec = Material_Spec;

            //MesCFG.BatchNo = BatchNo;
            _mesParameter.BatchNo = PC_No;
            _mesParameter.EmpNo = EmpNo;
            _mesParameter.Material_Code = Material_Code;
            try
            {
                _parameterStatic.Save();
            }catch(Exception ex)
            {
                $"预充机保存工单{_mesParameter.WorkOrder}失败！！！".RunLog(MessageLevelType.错误);
                Console.WriteLine(ex.ToString());
            }
            


            $"预充机保存工单{_mesParameter.WorkOrder}成功".RunLog(MessageLevelType.成功);

            _ = $"工单{_mesParameter.WorkOrder}保存成功！！！".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);

            _window.Close();
            //if (CFGLoader.Save(MesCFG))
            //{
            //    MyGrowl.SuccessGlobal("文件保存成功！");
            //}
            //else
            //{
            //    MyGrowl.WarningGlobal("文件保存失败！");
            //}
        });

        public Commands.DelegateCommand CmdUserCheck => new Commands.DelegateCommand(() =>
        {
            Dictionary<string, object> mesParam = new Dictionary<string, object>
                    {
                        { "EquipmentCode", _mesParameter.EquipmentCode==null?"": _mesParameter.EquipmentCode },
                        { "process_id", _mesParameter.process_id==null?"": _mesParameter.process_id },
                    };

            var mesParameters = new Dictionary<string, object>()
                {
                    {"WorkNumber",UserName }
                };

            mesParam.Add("parameter", mesParameters);
            var re = mesUserInteraction.MESInteraction(_parameterStatic.MESParameter.AccountRoute,
                 _parameterStatic.MESParameter.AccountTime,
                 1, DateTime.Now, mesParam);

            if (re == ResultTypes.合格)
            {
                _mesParameter.HasValidEmployeeId = 1;
                _mesParameter.HasValidUserName = UserName;
                MessageBox.Show("工号校验成功!");
            }
            else
            {
                _mesParameter.HasValidEmployeeId = 2;
                _mesParameter.HasValidUserName = null;
            }
        });

        public Commands.DelegateCommand CmdOrderSelectionChanged => new Commands.DelegateCommand(() =>
        {
            DoCmdOrderSelectionChanged();
        });


        /// <summary>
        /// 切换班组班次 OR 切换工单调用
        /// </summary>
        public void MESCountUpLoad_Hour()
        {
            //if (SystemConfig.SCM.IsShowWarnTip != false || SystemConfig.SCM.PerformTaskName?.Content.ToString() == "    运  行    ")
            //{
            //    _ = "请先点击运行，运行成功后，才能切换班组班次".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
            //    return;
            //}

            //var plcDataList = DeviceConfig.DeviceList.Where(x => x.DeviceType == DeviceTypes.KVPLC).ToList();

            var mesData_HourInteraction = new MESProductCountData_Hour(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);

            var mesData_DayInteraction = new MESProductCountData_Day(DialogLogHelper.MesLog
            , DialogLogHelper.MESDialog);

            var machineInfoType = MachineInfoTypes.预充装盘;

            var _parameter = _parameterStatic.MESCollectionItemsParameter[machineInfoType];

            $"{machineInfoType.ToString()}【切换班组班次】产量投入：{_parameter.InCount}  OK：{_parameter.OKCount}  NG：{_parameter.NGCount}".RunLog(MessageLevelType.成功);
            try
            {
                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                               new Dictionary<string, object>()
                                               {
                                                    { "Team", _parameter.ClassTeam },
                                                    { "Shift", _parameter.Class },
                                                    { "WorkNumber", _parameter.UserName },
                                                    { "EquipmentNo", _parameter.EquipmentCode },
                                                    { "WorkOrderNo", _parameter.WorkOrder },
                                                    { "PutIntoNumber", _parameter.InCount },
                                                    { "QualifiedNumber", _parameter.OKCount },
                                                    { "UnqualifiedNumber", _parameter.NGCount },
                                                    { "ProductionStartTime", DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss") },
                                                    { "ProductionEndTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },

                                                } 
                                        }
                                    }
                                };
                Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                    { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };



                var result = mesData_HourInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountDataRouter,
                     _parameterStatic.MESParameter.ProductCountDataTime,
                     1, DateTime.Now, mesParams);

                $"{machineInfoType.ToString()}【切换工单班组班次】生产统计小时上传MES成功投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
            }
            catch (Exception ex)
            {
                $"{machineInfoType.ToString()}【切换工单班组班次】生产统计小时小时小时上传MES错误：{ex}".RunLog(MessageLevelType.错误);
            }

            try
            {


                Dictionary<string, object> mesParameters = new Dictionary<string, object>
                                {
                                    { "data", new List<Dictionary<string, object>>()
                                        {
                                            new Dictionary<string, object>(){
                                            { "Team", _parameter.ClassTeam },
                                            { "Shift", _parameter.Class },
                                            { "WorkNumber", _parameter.UserName },
                                            { "EquipmentNo", _parameter.EquipmentCode },
                                            { "WorkOrderNo", _parameter.WorkOrder },
                                            { "PutIntoNumber", _parameter.InCount },
                                            { "QualifiedNumber", _parameter.OKCount },
                                            { "UnqualifiedNumber", _parameter.NGCount },
                                            }
                                        }
                                        
                                   },
                                };

                Dictionary<string, object> mesParams = new Dictionary<string, object>
                                {
                                  { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                        { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                    { "parameter", mesParameters }
                                };

                var result = mesData_DayInteraction.MESInteraction(_parameterStatic.MESParameter.ProductCountData_DayRouter,
                     _parameterStatic.MESParameter.ProductCountData_DayTime,
                     1, DateTime.Now, mesParams);

                $"{machineInfoType.ToString()}【下班上传产量】生产统计天天上传MES成功投入：{_parameter.PutIntoNumber}  OK：{_parameter.QualifiedNumber}  NG：{_parameter.UnqualifiedNumber}".RunLog(MessageLevelType.成功);
            }
            catch (Exception ex)
            {
                $"{machineInfoType.ToString()}【下班上传产量】生产统计天天天天上传MES错误：{ex}".RunLog(MessageLevelType.错误);
            }
            _parameter.InCount= 0;
            _parameter.OKCount= 0;
            _parameter.NGCount= 0;



        }

        /// <summary>
        /// 当前工单号选择值
        /// </summary>
        public string WorkorderSelectedValue { get; set; }
        /// <summary>
        /// 当前产品号选择值
        /// </summary>
        public string ProductMarkSelectedValue { get; set; }
        public string Bill_No { get; set; }
        public string Material_Code { get; set; }
        public string Material_Spec { get; set; }
        public string PC_No { get; set; }
        public string WorkOrderStatus_Name { get; set; }
        public string PlanedStart { get; set; }
        public string PlanedEndDate { get; set; }
        public string ProductionOrderNO { get; set; }

        public void DoCmdOrderSelectionChanged()
        {
            try
            {
                var index = lstBill_No.IndexOf(WorkorderSelectedValue);
                Bill_No = lstBill_No[index];
                Material_Code = lstMaterial_Code[index];
                Material_Spec = lstMaterial_Spec[index];
                PC_No = lstPC_No[index];
                WorkOrderStatus_Name = lstWorkOrderStatus_Name[index];
                PlanedStart = lstPlanedStart[index];
                PlanedEndDate = lstPlanedEndDate[index];
                ProductionOrderNO = lstProductionOrderNO[index];
            }
            catch (Exception)
            {

            }
        }


    }


    public class ComboxItem
    {
        public string Name { get; set; }
        public object Value { get; set; }

    }
}
